<template>
  <view class="flex-row flex-wrap" :style="{flexDirection:direction}">
    <view
      v-for="(item,index) in radios"
      :key="index"
      :class="{'margin-0':(index + 1) % row === 0}"
      :style="{margin}"
      class="margin-right-50"
    >
      <l-radio :checked="value===index" :padding="padding" :item="item" @click="change($event,index)" />
    </view>
  </view>
</template>

<script>
export default {
  name: 'LRadio',
  props: {
    radios: {
      type: Array,
      default: () => []
    },
    checked: {
      type: Number,
      default: 0
    },
    row: {
      type: Number,
      default: 2
    },
    margin: {
      type: String,
      default: ''
    },
    padding: {
      type: String,
      default: ''
    },
    direction: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      value: 0
    }
  },
  watch: {
    checked() {
      this.init()
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      const hasValue = this.radios[0].value
      if (hasValue || hasValue === 0) {
        this.radios.forEach((item, key) => {
          if (item.value === this.checked) this.value = key
        })
      } else {
        this.value = this.checked
      }
    },
    change(item, index) {
      this.value = index
      this.$emit('change', Object.assign(item, { index }))
    }
  }
}
</script>

<style scoped lang="scss">
.margin-0{
  margin-right:0!important;
}
</style>
